"""
监控管理API路由
"""

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from datetime import datetime, timedelta

from app.config import settings
from app.database import get_db
from app.models.monitor import Monitor, MonitorStatus, MonitorType
from app.schemas.monitor import MonitorCreate, MonitorResponse
# from app.tasks.monitor_tasks import check_product_updates, check_all_active_monitors

router = APIRouter()


@router.get("/status", summary="获取监控系统状态")
async def get_monitor_status():
    """获取监控系统整体状态"""
    try:
        from app.database import SessionLocal
        from app.models.monitor import Monitor, MonitorStatus
        from sqlalchemy import func

        db = SessionLocal()
        # 统计监控任务数量
        total_monitors = db.query(Monitor).count()
        active_monitors = db.query(Monitor).filter(Monitor.status == MonitorStatus.ACTIVE).count()

        # 最近24小时的统计
        yesterday = datetime.utcnow() - timedelta(days=1)
        recent_checks = db.query(Monitor).filter(
            Monitor.last_check_at >= yesterday
        ).count()

        db.close()

        return {
            "status": "running",
            "timestamp": datetime.utcnow().isoformat(),
            "statistics": {
                "total_monitors": total_monitors,
                "active_monitors": active_monitors,
                "inactive_monitors": total_monitors - active_monitors,
                "recent_checks_24h": recent_checks
            },
            "system_info": {
                "monitor_interval": settings.MONITOR_INTERVAL,
                "max_concurrent": settings.MAX_CONCURRENT_MONITORS,
                "notification_cooldown": settings.NOTIFICATION_COOLDOWN
            }
        }

    except Exception as e:
        return {
            "status": "error",
            "message": str(e),
            "timestamp": datetime.utcnow().isoformat()
        }


@router.post("/trigger-check", summary="手动触发监控检查")
async def trigger_monitor_check():
    """手动触发所有活跃监控的检查"""
    try:
        # 异步触发监控检查任务
        # task = check_all_active_monitors.delay()

        return {
            "status": "triggered",
            "task_id": "temp_disabled",
            "message": "监控检查任务已触发（临时禁用）",
            "timestamp": datetime.utcnow().isoformat()
        }

    except Exception as e:
        return {
            "status": "error",
            "message": str(e),
            "timestamp": datetime.utcnow().isoformat()
        }


@router.post("/{monitor_id}/check", summary="检查单个监控任务")
async def check_single_monitor(monitor_id: int):
    """手动检查单个监控任务"""
    try:
        # 异步触发单个监控检查
        # task = check_product_updates.delay(monitor_id)

        return {
            "status": "triggered",
            "monitor_id": monitor_id,
            "task_id": "temp_disabled",
            "message": f"监控任务 {monitor_id} 检查已触发（临时禁用）",
            "timestamp": datetime.utcnow().isoformat()
        }

    except Exception as e:
        return {
            "status": "error",
            "monitor_id": monitor_id,
            "message": str(e),
            "timestamp": datetime.utcnow().isoformat()
        }


@router.post("/", response_model=MonitorResponse, summary="创建监控")
async def create_monitor(
    monitor_data: MonitorCreate,
    db: Session = Depends(get_db)
):
    """创建新的监控任务（临时版本，固定绑定用户ID=2）"""
    try:
        # 固定用户ID为2（临时使用）
        user_id = 2

        # 创建监控任务
        monitor = Monitor(
            user_id=user_id,
            monitor_type=monitor_data.monitor_type,
            name=monitor_data.name or f"{monitor_data.monitor_type.value}监控",
            description=monitor_data.description,
            conditions=monitor_data.conditions.dict(),
            status=MonitorStatus.ACTIVE,  # 直接设为活跃状态
            is_active=True,
            duration_hours=monitor_data.duration_hours or 24,
            started_at=datetime.utcnow(),
            expires_at=datetime.utcnow() + timedelta(hours=monitor_data.duration_hours or 24)
        )

        db.add(monitor)
        db.commit()
        db.refresh(monitor)

        # 构建响应数据
        response_data = {
            "id": monitor.id,
            "user_id": monitor.user_id,
            "monitor_type": monitor.monitor_type,
            "name": monitor.name,
            "description": monitor.description,
            "conditions": monitor.conditions,
            "status": monitor.status,
            "is_active": monitor.is_active,
            "duration_hours": monitor.duration_hours,
            "started_at": monitor.started_at,
            "expires_at": monitor.expires_at,
            "created_at": monitor.created_at,
            "updated_at": monitor.updated_at,
            "last_check_at": monitor.last_check_at,
            "total_found": monitor.total_found,
            "total_notified": monitor.total_notified,
            "error_message": monitor.error_message,
            "error_count": monitor.error_count,
            "remaining_hours": (monitor.expires_at - datetime.utcnow()).total_seconds() / 3600 if monitor.expires_at else None,
            "is_expired": monitor.expires_at < datetime.utcnow() if monitor.expires_at else False
        }

        return response_data

    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建监控失败: {str(e)}"
        )


@router.get("/", response_model=List[MonitorResponse], summary="获取监控列表")
async def get_monitors(
    skip: int = 0,
    limit: int = 100,
    user_id: int = 2,  # 临时固定用户ID
    db: Session = Depends(get_db)
):
    """获取用户的监控列表（临时版本，固定用户ID=2）"""
    try:
        # 查询监控列表
        monitors = db.query(Monitor).filter(
            Monitor.user_id == user_id
        ).order_by(Monitor.created_at.desc()).offset(skip).limit(limit).all()

        # 构建响应数据
        response_data = []
        for monitor in monitors:
            monitor_data = {
                "id": monitor.id,
                "user_id": monitor.user_id,
                "monitor_type": monitor.monitor_type,
                "name": monitor.name,
                "description": monitor.description,
                "conditions": monitor.conditions,
                "status": monitor.status,
                "is_active": monitor.is_active,
                "duration_hours": monitor.duration_hours,
                "started_at": monitor.started_at,
                "expires_at": monitor.expires_at,
                "created_at": monitor.created_at,
                "updated_at": monitor.updated_at,
                "last_check_at": monitor.last_check_at,
                "total_found": monitor.total_found,
                "total_notified": monitor.total_notified,
                "error_message": monitor.error_message,
                "error_count": monitor.error_count,
                "remaining_hours": (monitor.expires_at - datetime.utcnow()).total_seconds() / 3600 if monitor.expires_at else None,
                "is_expired": monitor.expires_at < datetime.utcnow() if monitor.expires_at else False
            }
            response_data.append(monitor_data)

        return response_data

    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取监控列表失败: {str(e)}"
        )


@router.get("/{monitor_id}", response_model=MonitorResponse, summary="获取监控详情")
async def get_monitor(
    monitor_id: int,
    db: Session = Depends(get_db)
):
    """获取监控详情"""
    # TODO: 实现监控详情查询
    raise HTTPException(
        status_code=status.HTTP_404_NOT_FOUND,
        detail="监控不存在"
    )


@router.put("/{monitor_id}/start", summary="启动监控")
async def start_monitor(
    monitor_id: int,
    db: Session = Depends(get_db)
):
    """启动监控任务"""
    # TODO: 实现监控启动逻辑
    return {"message": "监控启动成功"}


@router.put("/{monitor_id}/stop", summary="停止监控")
async def stop_monitor(
    monitor_id: int,
    db: Session = Depends(get_db)
):
    """停止监控任务"""
    # TODO: 实现监控停止逻辑
    return {"message": "监控停止成功"}


@router.delete("/{monitor_id}", summary="删除监控")
async def delete_monitor(
    monitor_id: int,
    db: Session = Depends(get_db)
):
    """删除监控任务"""
    # TODO: 实现监控删除逻辑
    return {"message": "监控删除成功"}
